<template>
  <ContentDetailWrap :title="t('warehouse.add')">
    <!--    表单-->
    <el-form class="flex flex-wrap form-container" :model="form" ref="formRef" label-width="120px">
      <el-form-item :label="'发货商品'" class="w-80%" prop="product" required>
        <div class="w-full flex flex-col">
          <div class="w-full border rounded border-gray-200 p-4">
            <div class="flex items-center justify-between mb-4">
              <!-- 增加下边距 -->
              <div class="font-medium">
                <span class="text-gray-600">已选择 {{ form.product.length }} 个商品</span>
              </div>
              <!-- 加大且更明显的按钮 -->
              <el-button
                type="primary"
                icon="Plus"
                @click="handleOpenSalesPids"
                size="large"
                class="bg-blue-600 hover:bg-blue-700 text-white font-medium px-4 py-2 rounded shadow-md transition-all duration-300"
              >
                添加商品
              </el-button>
            </div>

            <!-- 商品展示区 -->
            <div v-if="form.product.length" class="w-full">
              <div
                v-for="(item, index) in form.product"
                :key="item.id"
                class="flex items-center justify-between p-4 mb-3 border border-gray-200 rounded hover:bg-gray-50"
              >
                <div class="flex-1 min-w-0 mr-4">
                  <div class="font-medium text-base mb-2">{{ item.cname }}</div>
                  <div class="grid grid-cols-2 gap-4 text-sm text-gray-500">
                    <div
                      >品牌: {{ brandList.find((b) => b.value === item.brand)?.label || '-' }}</div
                    >
                    <div
                      >仓库:
                      {{ warehouseList.find((w) => w.value === item.wid)?.label || '-' }}</div
                    >
                    <div
                      >类型:
                      {{
                        warehouseTypeList.find((t) => t.value === item.is_futures)?.label || '-'
                      }}</div
                    >
                    <div>到货日期: {{ item.arrival_date || '-' }}</div>
                    <div>实际到货日期: {{ item.real_arrival_date || '-' }}</div>
                    <div>头程物流费: ${{ formatCurrency(item.first_leg_logistics_fee) }}</div>
                  </div>
                </div>

                <!-- 数量控制 -->
                <div class="flex items-center">
                  <div class="text-sm text-gray-600 mr-3">数量</div>
                  <el-input-number
                    v-model="item.quantity"
                    :min="1"
                    size="large"
                    controls-position="right"
                    class="!w-140px"
                  />
                  <el-button
                    type="danger"
                    icon="Delete"
                    size="large"
                    circle
                    plain
                    @click="removeProduct(index)"
                    class="ml-3"
                  />
                </div>
              </div>
            </div>

            <!-- 空状态下的添加按钮也变大 -->
            <div
              v-else
              class="flex items-center justify-center py-8 border-2 border-dashed border-gray-300 rounded"
            >
              <el-button
                type="primary"
                icon="Plus"
                @click="handleOpenSalesPids"
                size="large"
                class="bg-blue-600 hover:bg-blue-700 text-white font-medium px-6 py-3 rounded-lg shadow-md"
              >
                添加商品
              </el-button>
            </div>
          </div>
        </div>
      </el-form-item>

      <el-form-item :label="t('logisticsRules.to_nation')" class="w-50%" prop="to_nation" required>
        <el-select
          v-model="form.to_nation"
          :filterable="true"
          :placeholder="t('logisticsRules.to_nation')"
          :clearable="false"
          :multiple="false"
        >
          <el-option
            v-for="item in toNationList"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>

      <!--      <el-form-item-->
      <!--        :label="t('logisticsRules.shipping_warehouse')"-->
      <!--        class="w-50%"-->
      <!--        prop="wid"-->
      <!--        required-->
      <!--      >-->
      <!--        <el-tree-select-->
      <!--          v-model="form.wid"-->
      <!--          :data="widList"-->
      <!--          filterable-->
      <!--          check-strictly-->
      <!--          :render-after-expand="false"-->
      <!--        />-->
      <!--      </el-form-item>-->

      <el-form-item :label="t('logisticsRules.terms')" class="w-50%" prop="terms" required>
        <el-select
          v-model="form.terms"
          :filterable="true"
          :placeholder="t('logisticsRules.terms')"
          :clearable="false"
          :multiple="false"
        >
          <el-option
            v-for="item in termsList"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>

      <el-form-item :label="'期望时效'" class="w-50%" prop="prescription" required>
        <el-select
          v-model="form.prescription"
          :filterable="true"
          :placeholder="'请输入期望时效'"
          :clearable="false"
          :multiple="false"
        >
          <el-option
            v-for="item in prescriptionList"
            :key="item.value"
            :label="item.label"
            :value="item.value"
            :disabled="item.value === 2"
          />
        </el-select>
      </el-form-item>

      <!-- 新增: 计算运费按钮 (仅当有商品时显示) -->
      <el-form-item label="" class="w-full">
        <div class="mt-6 flex justify-end">
          <el-button
            type="primary"
            size="large"
            @click="submit(formRef)"
            class="bg-blue-600 hover:bg-blue-700 text-white font-medium px-6 py-3 rounded shadow-md"
          >
            计算运费
          </el-button>
        </div>
      </el-form-item>
      <!-- 新增: 运费结果显示区域 -->
      <el-form-item v-if="freightResult !== null" label="运费计算结果:" class="w-full">
        <div class="text-xl font-bold text-red">
          头程物流费: ${{ formatCurrency(firstLegLogisticsFeeTotal) }} &nbsp;+ &nbsp;
          计算所得(派送段)运费: ${{ formatCurrency(deliveryFee) }} &nbsp;= &nbsp; 总运费: ${{
            formatCurrency(freightResult)
          }}
        </div>
      </el-form-item>
    </el-form>
  </ContentDetailWrap>

  <!--  商品选择弹框-->
  <DialogShopChecked
    ref="DialogShopCheckedRef"
    @expose-multiple-data="getExposeMultipleData"
    class="mobile-dialog"
  />
</template>

<script setup lang="ts">
import PrimarPidDialog from '@/components/Dialog/src/Fee.vue'
import DialogShopChecked from './DialogShopChecked/index.vue'
import { ContentDetailWrap } from '@/components/ContentDetailWrap'
import { ElMessage, ElLoading, type FormInstance } from 'element-plus'
import { getFieldEnumApi, logisticsFee } from '@/api/logisticsRules'
import { useRouter } from 'vue-router'
import { useI18n } from '@/hooks/web/useI18n'
import { ref, nextTick } from 'vue'
import { getInventoryEnumApi } from '@/api/wholesalOrder'
import { getEnumApi } from '@/api/warehouse/merchandiseOffers'

const { t } = useI18n()
const { go } = useRouter()

// 修改表单结构 - 新增运费结果变量
const freightResult = ref<number | null>(null)

const form = ref({
  prescription: 1,
  terms: 1,
  wid: '',
  to_nation: '',
  currency: 214,
  product: [] as Array<{
    id: number
    cname: string
    sku: string
    quantity: number
    first_leg_logistics_fee: number
    arrival_date: string | null
    real_arrival_date: string | null
    is_futures: number
    wid: number
    brand: number
    unique: string // Added unique property
  }>
})

// 添加列表数据
const brandList = ref<any[]>([])
const warehouseList = ref<any[]>([])
const warehouseTypeList = ref<any[]>([])

// 添加头程物流费计算结果
const firstLegLogisticsFeeTotal = ref<number>(0)

// 添加派送段运费
const deliveryFee = ref<number>(0)

const formRef = ref<FormInstance>()
interface Option {
  label: string
  value: string | number
  disabled?: boolean
}

const createOptions = (enumObject: { [key: string]: string }): Option[] => {
  return Object.keys(enumObject).map((key) => ({
    label: enumObject[key],
    value: parseInt(key, 10)
  }))
}
const salesPidsOptions = ref<any[]>([])
const prescriptionList = ref<any[]>([])
const termsList = ref<any[]>([])
const widList = ref<any[]>([])
const toNationList = ref<any[]>([])

const getDropDownBoxInfo = async () => {
  const resp = await getFieldEnumApi({ field: 'all' })
  toNationList.value = resp.data.to_nation
  termsList.value = createOptions(resp.data.terms)
  prescriptionList.value = createOptions(resp.data.prescription)

  // 获取品牌、仓库和类型列表
  const enumResp = await getInventoryEnumApi({ field: 'all' })
  brandList.value = enumResp.data.brand
  warehouseList.value = enumResp.data.wid
  warehouseTypeList.value = enumResp.data.is_futures

  const wresp = await getEnumApi({ field: 'warehouse_parent_tree' })
  if (!wresp?.data) return
  widList.value = wresp.data.warehouse_parent_tree
}

const DialogShopCheckedRef = ref<InstanceType<typeof DialogShopChecked>>()
//打开选择商品弹框
const handleOpenSalesPids = () => {
  nextTick(() => {
    DialogShopCheckedRef.value!.dialogVisible = true
    DialogShopCheckedRef.value!.initialize(form.value.product, form.value.currency)
  })
}

// 接收选择的商品数据
const getExposeMultipleData = (val: any[]) => {
  if (!val || !val.length) return
  const copyData = JSON.parse(JSON.stringify(form.value.product))
  const mergeData = copyData.concat(val)

  const duplicates = form.value.product.map((item: Record<string, any>) => item.unique)
  const newProducts = val.flatMap((item: Record<string, any>) => {
    if (duplicates.includes(item.unique)) {
      const existingProduct = form.value.product.find(
        (v: Record<string, any>) => item.unique === v.unique
      )
      return existingProduct ? [existingProduct] : []
    }
    return [
      {
        id: Number(item.product_id),
        cname: String(item.product_name),
        sku: String(item.product_code || 'N/A'),
        quantity: 1,
        first_leg_logistics_fee: Number(item.first_leg_logistics_fee) || 0,
        arrival_date: item.arrival_date,
        real_arrival_date: item.real_arrival_date,
        is_futures: Number(item.is_futures),
        wid: Number(item.wid),
        brand: Number(item.brand),
        unique: String(item.unique)
      }
    ]
  })

  form.value.product = newProducts
  calculateFirstLegLogisticsFee()
}

const removeProduct = (index: number) => {
  form.value.product.splice(index, 1)
}

// 计算头程物流费总和
const calculateFirstLegLogisticsFee = () => {
  firstLegLogisticsFeeTotal.value = form.value.product.reduce((total, item) => {
    return total + item.first_leg_logistics_fee * item.quantity
  }, 0)
}

// 修改: submit方法，添加运费计算逻辑
const submit = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate(async (valid) => {
    if (valid) {
      // 重置之前的运费结果
      freightResult.value = null
      deliveryFee.value = 0

      try {
        // 显示加载状态
        const loading = ElLoading.service({
          lock: true,
          text: '计算中...',
          background: 'rgba(0, 0, 0, 0.7)'
        })

        // 先计算头程物流费
        calculateFirstLegLogisticsFee()

        // 创建请求参数，移除头程物流费
        const requestProducts = form.value.product.map(
          ({ first_leg_logistics_fee, ...rest }) => rest
        )
        const params = {
          ...form.value,
          product: requestProducts
        } as unknown as Record<string, any>

        // 调用后端接口
        const resp = await logisticsFee(params)

        if (resp.code === 0) {
          // 假设接口返回运费在resp.data.logistics_fee中
          if (resp.data && resp.data.logistics_fee != 0) {
            // 保存派送段运费
            deliveryFee.value = resp.data.logistics_fee
            // 加上头程物流费得到总运费
            freightResult.value = deliveryFee.value + firstLegLogisticsFeeTotal.value
          } else {
            deliveryFee.value = 0
            freightResult.value = firstLegLogisticsFeeTotal.value
          }
        } else {
          ElMessage.error(t('logistics.rules.calculateFee'))
        }

        // 关闭加载状态
        loading.close()
      } catch (error) {
        ElMessage.error('运费计算过程中发生错误')
        console.error(error)
      }
    }
  })
}

// 修改运费结果显示
const formatCurrency = (value: number) => {
  return value.toFixed(2)
}

onMounted(() => {
  getDropDownBoxInfo()
})
</script>

<style lang="less" scoped>
.form-container {
  align-items: flex-start;

  :deep(.el-form-item__label) {
    font-weight: 500;
    color: #606266;
  }

  .el-form-item {
    margin-bottom: 20px;
  }

  // 按钮悬停效果增强
  .el-button--primary:hover {
    transform: translateY(-2px);
    box-shadow: 0 4px 12px rgb(59 130 246 / 50%);
  }

  // 输入框样式微调
  :deep(.el-input-number) {
    .el-input__inner {
      font-weight: 500;
      text-align: center;
    }
  }

  // 商品卡片样式
  .border-gray-200 {
    border-color: #e4e7ed;
  }

  .border-dashed {
    border-style: dashed;
  }
}
</style>
